// 后端接口
const exp = require('express');
const noteModel = require('./db/model/noteModel')

const app = exp();

app.use(exp.urlencoded({ extended: false }))
    // 4. 设置跨域中间件
app.use(function(request, response, next) {
    //     // access 访问进入  control 控制  allow 允许  origin 源
    response.setHeader('Access-Control-Allow-Origin', "*"); //任何页面发送请求都允许跨域请求
    // response.setHeader('Access-Control-Allow-Origin', "http://127.0.0.1:5500"); //指定域名可以发送请求允许跨域请求
    response.setHeader('Access-Control-Allow-Headers', "*"); //该响应头 允许客户端可以设置『自定义』请求头
    response.setHeader('Access-Control-Allow-Methods', "*"); //允许各种请求方式进行跨域请求 PUT  PATCH delete
    response.setHeader('Access-Control-Expose-Headers', "*"); //暴露响应头信息
    next();
});

// 添加笔记
app.post('/addNote', (req, res) => {
    // let { title, content } = req.body;
    noteModel.create(req.body, (err, data) => {
        if (err) {
            res.json({
                code: 2001,
                message: "添加笔记失败",
            })
        } else {
            res.json({
                code: 2000,
                message: "添加笔记成功",
                data
            })
        }
    })
})

// 查看笔记列表接口
app.get('/noteList', (req, res) => {

    let { page, limit } = req.query;

    let skip = page * limit;

    noteModel.find().skip(skip).limit(limit).exec((err, data) => {
        if (err) {
            res.json({
                code: 2001,
                message: "获取笔记失败",
            })
        } else {
            res.json({
                code: 2000,
                message: "获取笔记成功",
                data
            })
        }
    })
})

// 修改笔记接口
app.post('/updateNote', (req, res) => {
    let { title, content, id } = req.body;
    noteModel.updateOne({ _id: id }, { title, content }, (err, data) => {
        if (err) {
            res.json({
                code: 2001,
                message: "修改笔记失败",
            })
        } else {
            res.json({
                code: 2000,
                message: "修改笔记成功"
            })
        }
    })
})

// 删除笔记接口
app.get('/deleteNote', (req, res) => {
    let { id } = req.query;
    noteModel.deleteOne({ _id: id }, (err, data) => {
        if (err) {
            res.json({
                code: 2001,
                message: "删除笔记失败",
            })
        } else {
            res.json({
                code: 2000,
                message: "删除笔记成功"
            })
        }
    })
})

// 获取笔记详情接口
app.get('/detailNote', (req, res) => {
    let { id } = req.query;
    noteModel.findOne({ _id: id }, (err, data) => {
        if (err) {
            res.json({
                code: 2001,
                message: "获取笔记失败",
            })
        } else {
            res.json({
                code: 2000,
                message: "获取笔记成功",
                data
            })
        }
    })
})

app.listen(80, () => {
    console.log("启动成功");
})